<template>
  <el-dialog
    :title="titleMsg + '-' + $t('user.setRule')"
    :visible.sync="dialogVisible"
    :show="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :before-close="handleClose"
    width="335px"
    @open="open"
  >
    <el-form ref="form" v-loading="infoLoading">
      <el-button-group style="text-align: center">
        <el-button type="primary" size="small" @click="chooseAll">{{
          $t('user.selectAll')
        }}</el-button>
        <el-button type="primary" size="small" @click="cancelAll">{{
          $t('common.cancel')
        }}</el-button>
        <el-button type="primary" size="small" @click="mergeAll">{{
          $t('user.collapseAll')
        }}</el-button>
        <el-button type="primary" size="small" @click="unfoldAll">{{
          $t('user.expandAll')
        }}</el-button>
      </el-button-group>
      <div class="el-dialog-div">
        <el-scrollbar
          ref="myScrollbar"
          :wrap-class="{ wrapClass: true }"
          class="form-scrollbar"
        >
          <el-tree
            ref="tree"
            :data="initial"
            show-checkbox
            default-expand-all
            node-key="id"
            accordion
            highlight-current
            :props="defaultProps"
          />
        </el-scrollbar>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="12" class="btnEdit">
          <el-button :disabled="infoLoading" type="primary" @click="subInfo">{{
            $t('permission.confirm')
          }}</el-button>
        </el-col>
        <el-col :span="12" class="btnEdit">
          <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<style scoped>
.el-form {
  min-width: 270px;
}

.el-dialog-div {
  margin: 10px 0 10px 0;
  border: 1px solid #ebeef5;
}

.form-scrollbar {
  height: 400px;
}
</style>
<script>
import { postAction } from '@/api/common'
export default {
  name: 'authority',
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    // eslint-disable-next-line vue/require-prop-type-constructor
    id: {
      type: [Number, String],
      default: '',
    },
    userId: {
      type: [Number, String],
      default: '',
    },
  },
  data() {
    return {
      dialogVisible: this.show,
      isChange: false,
      initForm: true,
      initial: [],
      info: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      titleMsg: '',
      infoLoading: true,
    }
  },
  watch: {
    show() {
      this.dialogVisible = this.show
      this.initForm = true
    },
    info: {
      handler: function () {
        if (this.initForm) {
          this.isChange = false
          this.initForm = false
        } else {
          this.isChange = true
        }
      },
      deep: true,
    },
  },
  methods: {
    async open() {
      this.infoLoading = true
      // 页面重置
      this.$nextTick(() => {
        this.$refs.myScrollbar.wrap.scrollTop = 0
        this.$refs.form.clearValidate()
      })

      var list = {}
      var keys = {}

      if (this.id) {
        this.titleMsg = this.title
        const { data } = await postAction(
          { id: this.id },
          'ruleTemplate/GetAuthItems'
        )
        list = data.list
        //不要一级节点的key
        keys = data.keys
      } else {
        this.titleMsg = this.$t('user.user')
        const { data } = await postAction(
          { id: this.userId },
          'ruleTemplate/GetUserAuthItems'
        )
        list = data.list
        //不要一级节点的key
        keys = data.keys
      }
      console.log(keys, list)

      const t = []
      for (const index in list) {
        const item = list[index]
        if (item.children == null) {
          continue
        }
        const child = item.children.map((i) => {
          return {
            id: i.id,
            label: this.$t('route.' + i.lable),
            module: i.module,
            permissionFlag: i.permissionFlag,
          }
        })
        t.push({
          id: item.id,
          label: this.$t('route.' + item.lable),
          module: item.module,
          permissionFlag: item.permissionFlag,
          children: child,
        })
      }

      this.initial = t
      this.$refs.tree.setCheckedKeys(keys)

      this.infoLoading = false
    },
    async subInfo() {
      this.infoLoading = true
      // const data = {}
      const data = []
      const nodeFun = this.$refs.tree
      this.initial.forEach(function (item, index) {
        const key = item.id
        const node = nodeFun.getNode(key)
        if (node.checked || node.indeterminate) {
          data.push({
            module: item.module,
            permissionFlag: item.permissionFlag,
          })
          item.children.forEach(function (v, i) {
            const k = v.id
            const n = nodeFun.getNode(k)
            if (n.checked || n.indeterminate) {
              data.push({
                module: v.module,
                permissionFlag: v.permissionFlag,
              })
            }
          })
        }
      })

      if (this.id) {
        await postAction(
          { data: data, id: this.id },
          'ruleTemplate/SubAuthInfo'
        )
      } else {
        await postAction(
          { data: data, id: this.userId },
          'ruleTemplate/SubUserAuthInfo'
        )
      }

      this.infoLoading = false
      // 调用父级页面方法
      this.closeAction()
      this.$notify({
        title: this.$t('common.success'),
        message: this.$t('common.operationSuccess'),
        type: 'success',
        duration: 2000,
      })
    },
    chooseAll() {
      const arr = []
      for (const value of this.initial) {
        arr.push(value.id)
      }
      this.$refs.tree.setCheckedKeys(arr)
    },
    cancelAll() {
      this.$refs.tree.setCheckedKeys([])
    },
    mergeAll() {
      for (let i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
        this.$refs.tree.store._getAllNodes()[i].expanded = false
      }
    },
    unfoldAll() {
      for (let i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
        this.$refs.tree.store._getAllNodes()[i].expanded = true
      }
    },
    handleClose(done) {
      if (this.isChange) {
        this.$confirm(this.$t('common.unsavedChangesTip'), this.$t('common.tips'), {
          type: 'warning',
        })
          .then((_) => {
            this.$emit('update:show', false)
          })
          // eslint-disable-next-line @typescript-eslint/no-empty-function
          .catch((_) => {})
      } else {
        this.$emit('update:show', false)
      }
    },
    closeAction() {
      this.$emit('closeAction')
    },
  },
}
</script>
